<template>
  <div>
    <Modal :mask-closable="false" v-model="opened" :title="title" class="modal-content-layout" width="80%">
      <div class="t-r mb16">
        <!--               <span class="creatBtnright" @click="addScoreCategory">-->
        <!--                   <span><Icon type="ios-add-circle-outline"/></span>-->
        <!--                   &lt;!&ndash; 新增类别 &ndash;&gt;-->
        <!--                   <span class="rightbtn">{{$t('ledger.NewCategory')}}</span>-->
        <!--               </span>-->
        <Button @click="addScoreCategory" type="primary">{{ $t('ledger.NewCategory') }}</Button>
      </div>

      <div class="tableContent">
        <table class="scoreTable" style="width:100%">
          <tr>
            <th class="head"> &nbsp;</th>
            <th class="head">{{ $t('ledger.Category') }}</th> <!-- 类别 -->
            <th class="head">{{ $t('ledger.Abbreviation') }}</th> <!-- 简称 -->
            <th class="head">{{ $t('ledger.Weight') }}</th> <!-- 比例 -->
            <th class="head">{{ $t('角色') }}</th> <!-- 比例 -->
            <th class="head">{{ $t('common.operation') }}</th> <!-- 操作 -->
          </tr>

          <tr v-for="(item, index) in dmsDeviceScoreConfig.dmsDeviceScoreCategoryList" :key="index">
            <td class="cell">
              {{ index + 1 }}
            </td>
            <td class="cell">
              <Input style="border:#dcdee2 solid 1px;" v-model="item.categoryName"
                :placeholder="`${$t('common.inputInfo')}`" />
            </td>
            <td class="cell">
              <Input style="border:#dcdee2 solid 1px;" v-model="item.categoryShortName"
                :placeholder="`${$t('common.inputInfo')}`" />
            </td>
            <td class="cell">
              <Input style="border:#dcdee2 solid 1px;" type="number" v-model="item.categoryRate"
                :placeholder="`${$t('common.inputInfo')}`" max="100" min="0">
              <span slot="suffix" class="suffix">%</span>
              </Input>
            </td>
            <td class="cell">
              <Select style="border:#dcdee2 solid 1px;width: 250px;text-align: left" multiple v-model="item.roleIds">
                <Option style="text-align: left" v-for="item in rolesList" :value="item.id" :key="item.id">{{ item.name }}
                </Option>
              </Select>
            </td>
            <td class="cell">
              <Button type="text" class="operationBtn" @click="openScoreItem(item, index)">
                {{ $t('ledger.EditScoring') }}
              </Button><!-- 编辑评分项目及标准 -->
              <Button type="text" class="operationBtn" @click="deleted(index)">{{ $t('common.Delete') }}</Button>
              <!-- 删除 -->
            </td>
          </tr>
        </table>
      </div>


      <div slot="footer">
        <Button type="default" @click="close">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="submitLoading" @click="submit">{{ $t('maintenance.Confirmed') }}</Button>
      </div>

      <Spin size="large" fix v-if="spinShow"></Spin>
    </Modal>

    <score-item ref="scoreItem" @save="saveScoreItem"></score-item>
  </div>
</template>

<script>
import ScoreItem from "./scoreItem";
import { saveOrUpdate, detail, updateScore } from "../../../../../api/dev-basic/score-config";

export default {
  name: 'scoreCategory',
  components: {
    ScoreItem
  },
  data() {
    return {
      dmsDeviceScoreConfig: {
        dmsDeviceScoreCategoryList: [{
          categoryName: '',
          categoryShortName: '',
          categoryRate: '',
          dmsDeviceScoreItemList: [{
            itemName: '',
            itemShortName: '',
            itemRate: '',
            roleIds: [],
            dmsDeviceScoreStandardList: [{
              grade: '',
              standardDesc: ''
            }]
          }]
        }]
      },
      spinShow: false,
      currentIndex: 0,
      submitLoading: false,
      opened: false,
      title: '',
      rolesList: []
    }
  },
  methods: {
    open(title, dmsDeviceScoreConfigId) {
      this.getRoles()

      this.dmsDeviceScoreConfig = {
        dmsDeviceScoreCategoryList: [{
          categoryName: '',
          categoryShortName: '',
          categoryRate: '',
          dmsDeviceScoreItemList: [{
            itemName: '',
            itemShortName: '',
            itemRate: '',
            dmsDeviceScoreStandardList: [{
              grade: '',
              standardDesc: ''
            }]
          }]
        }]
      };

      if (dmsDeviceScoreConfigId) {
        this.spinShow = true;
        this.getDetail(dmsDeviceScoreConfigId);
      }

      this.title = title;
      this.opened = true;
    },
    close() {
      this.opened = false;
    },
    getDetail(dmsDeviceScoreConfigId) {
      let params = {
        dmsDeviceScoreConfigId: dmsDeviceScoreConfigId,
        sourceType: 0
      }
      detail(params).then(res => {
        const data = res.data;
        data.dmsDeviceScoreCategoryList.forEach(item => {
          item.roleIds = item.roleVos.map(item => { return item.id })
        })
        this.dmsDeviceScoreConfig = data;
        this.spinShow = false;
      })
    },
    getRoles() {
      this.axios({
        method: "get",
        url: "/basic/role/page?pageNum=1&pageSize=100&status=1",
        params: {}
      }).then(res => {
        if (res.code === 200) {
          this.rolesList = res.data.list
        }
      });
    },
    submit() {

      let rateCount = 0;
      if (this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList && this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList.length > 0) {
        for (let category of this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList) {
          if (!category.categoryName || !category.categoryShortName || (!category.categoryRate && Number(category.categoryRate !== 0))) {
            this.$Message.warning(({ content: '有未填项，无法保存', duration: 6, closable: true }));
            return false;
          }

          let dmsDeviceScoreItemList = category.dmsDeviceScoreItemList;
          if (dmsDeviceScoreItemList && dmsDeviceScoreItemList.length > 0) {
            for (let item of dmsDeviceScoreItemList) {

              if (!item.itemName || !item.itemShortName || (!item.itemRate && Number(item.itemRate !== 0))) {
                this.$Message.warning(({
                  content: category.categoryName + '，评分项目未填写，无法保存',
                  duration: 6,
                  closable: true
                }));
                return false;
              }

              let dmsDeviceScoreStandardList = item.dmsDeviceScoreStandardList;
              if (dmsDeviceScoreStandardList && dmsDeviceScoreStandardList.length > 0) {
                for (let standard of dmsDeviceScoreStandardList) {
                  if (!standard.grade || !standard.standardDesc) {
                    this.$Message.warning(({ content: item.itemName + '，评分标准未填写，无法保存', duration: 6, closable: true }));
                    return false;
                  }
                }
              }


            }
          }
          rateCount += Number(category.categoryRate);
        }
      }

      console.log(rateCount);
      if (Number(rateCount) !== 100) {
        this.$Message.warning(({ content: '比例总和不等于100%', duration: 6, closable: true }));
        return false;
      }

      this.submitLoading = true;
      const fun = this.dmsDeviceScoreConfig.id ? updateScore : saveOrUpdate
      fun(this.dmsDeviceScoreConfig).then(res => {
        ;
        if (res.code === 200) {
          this.opened = false;

          this.$emit('change')
        } else {
          this.createByOptions = []
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
        this.submitLoading = false;
      }).catch(err => {
        this.submitLoading = false;
        console.error(err);
      });
    },
    openScoreItem(item, index) {
      this.currentIndex = index;
      this.$refs.scoreItem.open('评分项目配置', JSON.parse(JSON.stringify(item.dmsDeviceScoreItemList)));
    },
    saveScoreItem(dmsDeviceScoreItemList) {
      this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList[this.currentIndex].dmsDeviceScoreItemList = dmsDeviceScoreItemList;
    },
    addScoreCategory() {
      this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList.push({
        categoryName: '',
        categoryShortName: '',
        categoryRate: '',
        dmsDeviceScoreItemList: [{
          itemName: '',
          itemShortName: '',
          itemRate: '',
          dmsDeviceScoreStandardList: [{
            grade: '',
            standardDesc: ''
          }]
        }]
      });
    },
    deleted(index) {
      this.dmsDeviceScoreConfig.dmsDeviceScoreCategoryList.splice(index, 1);
    }
  }
}
</script>

<style scoped lang="scss">
/*.scoreTable {*/
/*    width: 100%;*/
/*}*/

/*.head {*/
/*    background-color: #f3f3f8;*/
/*    min-height: 50px;*/
/*    text-align: center;*/
/*    line-height: 50px;*/
/*}*/

/*.cell {*/
/*    text-align: center;*/
/*    line-height: 50px;*/
/*    padding: 10px 10px 10px 10px;*/
/*    border: 1px solid #b7b7b7;*/
/*    border-collapse: collapse;*/
/*}*/

.cell .suffix {
  display: block;
  line-height: 30px;
}

/*.operationBtn {*/
/*    color: #1c82f9;*/
/*}*/

th {
  padding: 8px 0;
  text-align: center;
}

td {
  padding: 8px 18px;
  text-align: center;
}
</style>
